package com.tbit.uqbike.client.handler.borrowbikehandler;

import com.alibaba.fastjson.JSON;
import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.common.ResultMsg;
import com.tbit.uqbike.client.constant.AccountConfigExtConstant;
import com.tbit.uqbike.client.constant.MachineStateConstant;
import com.tbit.uqbike.client.constant.RedisConstant;
import com.tbit.uqbike.client.dao.core.BorrowCheckConfigLogDao;
import com.tbit.uqbike.client.dao.core.MachineFunctionDao;
import com.tbit.uqbike.client.pojo.Machine;
import com.tbit.uqbike.client.pojo.MachineFunction;
import com.tbit.uqbike.client.pojo.TerLastStatus;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.borrowbike.BorrowCheckConfigLog;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.pojo.newEntity.BleHelmet;
import com.tbit.uqbike.client.service.BleHelmetService;
import com.tbit.uqbike.client.service.CacheService;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.util.ObjectUtil;
import com.tbit.uqbike.client.util.RedisUtil;
import com.tbit.uqbike.client.vo.borrow.BorrowBikeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lh2
 * @ClassName: HelmetCheckHandler
 * @Description: 头盔故障校验处理器
 * @date 2023-07-27 03:02:38
 */
@Slf4j
@Component
public class HelmetCheckHandler extends AbstractCheckHandler {
    @Autowired
    private RedisService redisService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private BleHelmetService bleHelmetService;
    @Autowired
    private MachineFunctionDao machineFunctionDao;
    @Autowired
    private BorrowCheckConfigLogDao borrowCheckConfigLogMapper;

    @Override
    public ResultMsg handle(BorrowBikeVO vo, String serialNO) {
        log.info("【头盔故障校验处理器】校验开始...");
        // 降级：如果配置了降级，则跳过此处理器，执行下一个处理器
        if (super.getConfig().getDown() == 1) {
            log.info("【头盔故障校验处理器】被降级，已自动跳过！");
            return super.next(vo, serialNO);
        }

        User user = vo.getUser();
        Machine machine = vo.getMachine();
        // 头盔锁故障校验
        Map<String, Object> param = new HashMap<>();
        param.put("machineId", machine.getMachineId());
        param.put("functionType", MachineStateConstant.MACHINE_TYPE_BLE_HELMET);
        MachineFunction function = machineFunctionDao.getByMachineId(param);
        AccountConfigExt accountConfigExt = cacheService.getAccountConfigExtByKey(machine.getAccountId(),
                AccountConfigExtConstant.ACCOUNTCONFIG_HELMET);
        if (function != null) {
            BleHelmet bleHelmet = bleHelmetService.getByUserCode(vo.getUserCode());
            if (bleHelmet != null) {
                String tmp = redisService.get(RedisConstant.RIDELOG_BEFORE_BORROW_STATUS + machine.getMachineNO());
                if ((accountConfigExt != null && accountConfigExt.getParamValue().equalsIgnoreCase("1")
                        && (tmp == null || !ObjectUtil.statusParse(0, Integer.valueOf(tmp))))) {
                    return ResultMsg.fail(-140002, "头盔锁故障,请换一辆车骑行", TraceUtil.getTraceIdByLocal());
                }
            }
        } else {
            String json = redisService.getMain(RedisUtil.getTerHashId(machine.getMachineNO()),
                    RedisConstant.REDIS_TER_LAST_STATUS);
            if ((json != null && json.length() > 0)) {
                TerLastStatus terLastStatus = JSON.parseObject(json, TerLastStatus.class);
                Integer terStatus = terLastStatus.getCarStatus();
                /** 头盔锁缓存 */
                redisService.addMain(RedisConstant.MACHINE_NO_HELMET + user.getUserId(), terStatus.toString(),
                        24 * 60 * 60);

                if ((accountConfigExt != null && accountConfigExt.getParamValue().equalsIgnoreCase("1")
                        && ObjectUtil.statusParse(11, Integer.valueOf(terStatus)))) {
                    return ResultMsg.fail(-140002, "头盔锁故障,请换一辆车骑行",TraceUtil.getTraceIdByLocal());
                }
            } else {
                log.warn(machine.getMachineNO() + "未获取到车辆状态");
            }
        }

        log.info("【头盔故障校验处理器】校验通过！");
        BorrowCheckConfigLog bccLog = borrowCheckConfigLogMapper.findByNameAndSerialNO(
                this.getConfig().getHandlerName(), serialNO);
        if (bccLog != null) {
            bccLog.setExecuteResult(1);
            borrowCheckConfigLogMapper.updateByPrimaryKeySelective(bccLog);
        }
        // 执行下一个处理器
        return super.next(vo, serialNO);
    }
}
